package top.kaoshanji.q1ch03a.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import top.kaoshanji.q1ch03a.domain.User;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author kaoshanji
 * ^_^
 * create time 2025/5/3 17:55
 */
@Repository
public class UserDao {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // 根据用户名和密码查询用户数量的SQL语句
    private final static String MATCH_COUNT_SQL = " SELECT count(*) FROM t_user WHERE user_name =? and password=? ";

    /**
     * 根据用户名和密码查询用户数量
     * @param userName userName
     * @param passWord passWord
     * @return 大于0说明存在该用户
     */
    public int getMatchCount(String userName, String passWord) {
        return jdbcTemplate.queryForObject(MATCH_COUNT_SQL, Integer.class, userName, passWord);
    }

    // 根据用户名查找用户的SQL语句
    private final static String FIND_USER_BY_USERNAME_SQL = " SELECT user_id,user_name,credits FROM t_user WHERE user_name =? ";

    /**
     * 根据用户名查找用户
     * @param userName userName
     * @return User
     */
    public User findUserByUserName(String userName) {
        User user = new User();

        jdbcTemplate.query(FIND_USER_BY_USERNAME_SQL, new Object[]{userName},
                new RowCallbackHandler() {
                    @Override
                    public void processRow(ResultSet rs) throws SQLException {
                        user.setUserId(rs.getInt("user_id"));
                        user.setUserName(rs.getString("user_name"));
                        user.setCredits(rs.getInt("credits"));
                    }
                });

        return user;
    }

    // 更新用户信息的SQL语句
    private  final static String UPDATE_LOGIN_INFO_SQL = " UPDATE t_user SET last_visit=?,last_ip=?,credits=? WHERE user_id =? ";

    /**
     * 更新用户信息
     * @param user User
     */
    public void updateLoginInfo(User user) {
        jdbcTemplate.update(UPDATE_LOGIN_INFO_SQL, user.getLastVisit(), user.getLastIp(), user.getCredits(), user.getUserId());
    }


}
